/**
 * 
 */
package org.drl.tvkit.dao;

import java.util.LinkedList;
import java.util.List;

import org.drl.tvkit.KitApplication;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


/**
 * @author dai.rui.lin
 * 
 */
public class DataBaseManager extends SQLiteOpenHelper {
	
	public static final void newBuilder(){
		DataBaseManager.getInstance();
		DataBaseManager.getInstance().addTable(UserTable.getInstance());
		DataBaseManager.getInstance().addTable(KeyValueTable.getInstance());
		DataBaseManager.getInstance().addTable(ApplicationTable.getInstance());
		DataBaseManager.getInstance().addTable(ShortTable.getInstance());
		DataBaseManager.getInstance().addTable(FileRecordTable.getInstance());
		ApplicationTable.getInstance().updataCounts();
	}
	
	
	private static String DATABASE_NAME = "mkittv.db";
	private static final int DATABASE_VERSION = 1;

	private final List<DatabaseTable> registeredTables;

	private static DataBaseManager instance;

	public static DataBaseManager getInstance() {
		if (instance == null) {
			instance = new DataBaseManager();
		}
		return instance;
	}

	public static final void reInit(String name) {
		if (instance != null) {
			instance.close();
		}
		DATABASE_NAME = name;
		instance = new DataBaseManager();
	}

	public DataBaseManager() {
		super(KitApplication.getInstance(), DATABASE_NAME, null,
				DATABASE_VERSION);
		registeredTables = new LinkedList<DatabaseTable>();
	}

	public void addTable(DatabaseTable table) {
		registeredTables.add(table);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		for (DatabaseTable table : registeredTables) {
			table.create(db);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if (newVersion > oldVersion) {
			for (DatabaseTable table : registeredTables) {
				table.migrate(db, oldVersion);
			}

			onCreate(db);
		}
	}

	public static void execSQL(SQLiteDatabase db, String sql) {
		db.execSQL(sql);
	}

	public static void dropTable(SQLiteDatabase db, String table) {
		execSQL(db, "DROP TABLE IF EXISTS " + table + ";");
	}

	public static void renameTable(SQLiteDatabase db, String table,
			String newTable) {
		execSQL(db, "ALTER TABLE " + table + " RENAME TO " + newTable + ";");
	}

	public void onClear() {
		for (DatabaseTable table : registeredTables)
			table.clear();
	}

//	public void onLoad() {
//		try {
//			getWritableDatabase(); // Force onCreate or onUpgrade
//		} catch (SQLiteException e) {
//			if (e == DOWNGRAD_EXCEPTION) {
//				// Downgrade occured
//			} else {
//				throw e;
//			}
//		}
//	}

}
